import React, { useState } from 'react';
import { Layout, Card, Form, Input, Button, message } from 'antd';
import { LockOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { authApi } from '../services/api';
import '../index.css';

const { Content } = Layout;

interface LoginFormValues {
  password: string;
}

const Login: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  const handleSubmit = async (values: LoginFormValues) => {
    const { password } = values;
    setLoading(true);

    try {
      // 调用后端登录API
      const response = await authApi.login(password);
      
      // 保存token
      localStorage.setItem('auth_token', response.token);
      localStorage.setItem('auth_time', Date.now().toString());
      
      message.success('登录成功');
      
      // 重定向到之前想要访问的页面，如果没有则重定向到首页
      const from = location.state?.from?.pathname || '/';
      navigate(from, { replace: true });
    } catch (error: any) {
      console.error('Login error:', error);
      const errorMessage = error?.response?.data?.detail || '登录失败，请检查密码';
      message.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Layout style={{ minHeight: '100vh', background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }}>
      <Content 
        style={{ 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'center',
          padding: '20px'
        }}
      >
        <Card
          style={{
            width: '100%',
            maxWidth: 400,
            borderRadius: '12px',
            boxShadow: '0 8px 32px rgba(0,0,0,0.1)'
          }}
        >
          <div style={{ textAlign: 'center', marginBottom: 32 }}>
            <div style={{ fontSize: 48, marginBottom: 16 }}>🔐</div>
            <h1 style={{ fontSize: 24, fontWeight: 600, margin: 0, color: '#1f1f1f' }}>
              参数管理系统
            </h1>
            <p style={{ color: '#8c8c8c', marginTop: 8, marginBottom: 0 }}>
              请输入密码以继续
            </p>
          </div>

          <Form
            form={form}
            name="login"
            onFinish={handleSubmit}
            layout="vertical"
            size="large"
            autoComplete="off"
          >
            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入密码' }
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="请输入密码"
                autoComplete="new-password"
              />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                block
                loading={loading}
                style={{
                  height: 44,
                  borderRadius: '6px',
                  fontSize: '16px',
                  fontWeight: 500
                }}
              >
                登录
              </Button>
            </Form.Item>
          </Form>

          <div style={{ textAlign: 'center', marginTop: 16 }}>
            <p style={{ fontSize: 12, color: '#8c8c8c', margin: 0 }}>
              ⚠️ 未经授权的访问将被拒绝
            </p>
          </div>
        </Card>
      </Content>
    </Layout>
  );
};

export default Login;

